from pydantic_settings import BaseSettings, SettingsConfigDict
import pathlib, os, yaml
import logging
import logging.config
from typing import Optional
from passlib.context import CryptContext

BASE_DIR = pathlib.Path(__file__).parent.parent

class Settings(BaseSettings):
    model_config = SettingsConfigDict(env_file=".env")
    PROJECT_NAME: str
    HOST: str
    PORT: int
    # HF
    MODEL_PATH: str
    #
    IS_DEBUG: bool
    CORS_ORIGINS: str
    # 附件是本地存储?MinIo?
    STORAGE: str
    # API对外公开的基地址
    BASE_URL: str
    # 上传的最大数量
    MAX_UPLOAD_SIZE: int
    # MINIO
    MINIO_Endpoint: str
    MINIO_Access_Key: str
    MINIO_Secret_Key: str
    MINIO_Secure: bool
    MINIO_Bucket: str
    # JWT AUTH
    AUTH_ACCESS_TOKEN_EXPIRE_MINUTES: int
    AUTH_REFRESH_TOKEN_EXPIRE_MINUTES: int
    AUTH_ALGORITHM: str
    AUTH_JWT_SECRET_KEY: str
    AUTH_JWT_REFRESH_SECRET_KEY: str
    # REDIS
    REDIS_HOST: str
    REDIS_PORT: Optional[int] = 6379
    REDIS_USERNAME: Optional[str] = None
    REDIS_PASSWORD: Optional[str] = None
    REDIS_DB: Optional[int] = 1
def setup_log(app_name:str='traine')->None:
    DEFAULT_LOG_PATH = BASE_DIR / 'config' / 'logging.yaml'
    
    default_log_config:dict = {
            'version': 1,
            'filename': f'/logs/{app_name}.txt',
            'filemode': 'a',
            'format': '%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
            'datefmt': '%H:%M:%S',
            'level': logging.DEBUG
    }
    if os.path.exists(DEFAULT_LOG_PATH):
        with open(DEFAULT_LOG_PATH, 'rt') as f:
            try:
                config = yaml.safe_load(f.read())
                logging.config.dictConfig(config)
            except Exception as e:
                logging.config.dictConfig(default_log_config)
                print('Error in Logging Configuration. Using default configs, exception:%s, message:%s, path:%s' % (repr(e), str(e), DEFAULT_LOG_PATH))

    else:
        logging.config.dictConfig(default_log_config)
        print('Failed to load configuration file. Using default configs')


settings = Settings()
password_context = CryptContext(schemes=["bcrypt"], deprecated="auto")